package com.whut.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.whut.common.ReportCommonFunc;
import com.whut.mapper.*;
import com.whut.model.*;
import com.whut.parMapper.ParProblemCollectDetailMapper;
import com.whut.parMapper.ParProblemDescriptionMapper;
import com.whut.parMapper.ParSystemMapper;
import com.whut.parMapper.utils.MapperUtils;
import com.whut.report.*;
import com.whut.service.EquipService;
import com.whut.service.NewFuzzyService;
import com.whut.service.ReportService;
import com.whut.utils.*;
import com.whut.v_model.CheckAndProject;
import com.whut.v_model.ProblemCollectDetail;
import org.apache.commons.lang3.StringUtils;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;


@Service("reportService")
public class ReportServiceImpl implements ReportService {

    private ParSystemMapper parSystemMapper;

    private ParProblemDescriptionMapper parProblemDescriptionMapper;

    public static final int WIDTH = 718;
    public static final int HEIGHT = 468;

    @Resource
    private MapperUtils mapperUtils;
    @Resource
    private ContracttaskprojectMapper contractTaskProjectMapper;
    @Resource
    private ContracttaskacceptMapper contracttaskacceptMapper;
    @Resource
    private ProblemCollectDetailMapper problemCollectDetailMapper;
    @Resource
    private PrefixParSystemMapper prefixParSystemMapper;
    @Resource
    private NewPrefixSystemMapper newPrefixSystemMapper;
    @Resource
    private ContractchecktaskMapper contractchecktaskMapper;
    @Resource
    private GroupMemberDetailMapper groupMemberDetailMapper;
    @Resource
    private ContractinfoMapper contractinfoMapper;
    @Resource
    private UncheckeditemsMapper uncheckeditemsMapper;
    @Resource
    private AllpointsaveMapper allpointsaveMapper;
    @Resource
    private PointlimitMapper pointlimitMapper;
    @Resource
    private SummaryMapper summaryMapper;
    @Resource
    private EquipinfoMapper equipinfoMapper;
    @Resource
    private FuzzyresultMapper fuzzyresultMapper;
    @Resource
    private MeasuretablerecordMapper measuretablerecordMapper;
    @Resource
    private EditableweightpsMapper editableweightpsMapper;
    @Resource
    private MachineinfoMapper machineinfoMapper;
    @Resource
    private NoproblemitemMapper noproblemitemMapper;
    @Resource
    private NewProblemDescriptionMapper newproblemdescriptionMapper;
    @Resource
    private ProblemDescriptionMapper problemDescriptionMapper;
    @Resource
    private EquipscoreMapper equipscoreMapper;
    @Resource
    private NewFuzzyService newFuzzyService;
    @Resource
    private EquipService equipService;
    @Resource
    private NewProblemCollectDetailMapper newProblemCollectDetailMapper;
    @Resource
    private UrlProperties urlProperties;
    @Resource
    private Profiles profiles;
    @Resource
    private ImgFile imgFile;


    @Override
    public Object getAllCheckInfoForReport(String client, String task, String check, String startTime, String endTime) {
        List<CheckAndProject> list = new ArrayList<>();
        JSONArray jsonArray1 = JSONArray.parseArray(client);
        int contractId = jsonArray1.getIntValue(0);
        JSONArray jsonArray2 = JSONArray.parseArray(task);
        List<Integer> list2 = new ArrayList<>();
        for (int i = 0; i < jsonArray2.size(); i++) {
            list2.add(jsonArray2.getIntValue(i));
        }
        JSONArray jsonArray3 = JSONArray.parseArray(check);
        List<Integer> list3 = new ArrayList<>();
        for (int j = 0; j < jsonArray3.size(); j++) {
            list3.add(jsonArray3.getIntValue(j));
        }
        if (task.equals("[]") && check.equals("[]")) {
            list = contractTaskProjectMapper.getAllProjectForReportOnlyByClientAndTime(contractId, startTime, endTime);
        } else if (!task.equals("[]") && check.equals("[]")) {
            list = contractTaskProjectMapper.getAllProjectForReportOnlyByClientAndTaskAndTime(contractId, startTime, endTime, list2);
        } else if (!task.equals("[]") && !check.equals("[]")) {
            list = contractTaskProjectMapper.getAllProjectForReportOnlyByClientAndTaskAndAndCheckTime(contractId, startTime, endTime, list2, list3);
        }
        return list;
    }

    @Override
    public String getSecurityReport(String client,String check,String checkInfo,boolean isNew) throws UnsupportedEncodingException {
        ParSystemMapper parSystemMapper = isNew ? newPrefixSystemMapper : prefixParSystemMapper;
        ParProblemDescriptionMapper parProblemDescriptionMapper = isNew ? newproblemdescriptionMapper : problemDescriptionMapper;
        ParProblemCollectDetailMapper parProblemCollectDetailMapper = isNew ? newProblemCollectDetailMapper : problemCollectDetailMapper;
        return new SecurityReport(parSystemMapper,
                parProblemDescriptionMapper,
                parProblemCollectDetailMapper,
                this,
                mapperUtils,
                urlProperties,
                profiles).getSecurityReport(client,check,checkInfo,isNew);
    }



    @Override
    public String rectificationNoticeCreate(int checkId, boolean isNew) throws UnsupportedEncodingException {
        ParSystemMapper parSystemMapper = isNew ? newPrefixSystemMapper : prefixParSystemMapper;
        ParProblemDescriptionMapper parProblemDescriptionMapper = isNew ? newproblemdescriptionMapper : problemDescriptionMapper;
        ParProblemCollectDetailMapper parProblemCollectDetailMapper = isNew ? newProblemCollectDetailMapper : problemCollectDetailMapper;
        return new RectificationNoticeCreateReport(parSystemMapper,
                parProblemDescriptionMapper,
                parProblemCollectDetailMapper,
                this,
                mapperUtils,
                urlProperties,
                profiles).rectificationNoticeCreate(checkId, isNew);
    }

    @Override
    public String supervisionSpotCheckOfSgseftyInJsproject(int checkId, boolean isNew) throws UnsupportedEncodingException {
        HashMap<String, Object> dataMap = new HashMap<>();
        List<ContractTaskProject> header = contractTaskProjectMapper.getHeader(checkId);
        String projectName = header.get(0).getProjectName();
        String progress = header.get(0).getProgress();
        String checkTime = header.get(0).getCheckTime();
        dataMap.put("projectName", projectName);
        dataMap.put("progress", progress);
        dataMap.put("checkTime", checkTime);
        List<ProblemCollectDetail> getPCD = problemCollectDetailMapper.getPCDByCheckId(checkId);
        String pName4 = "";
        int temp = 0;
        List<Object> checkList = new ArrayList<>();
        for (ProblemCollectDetail p : getPCD) {
            HashMap<String, Object> checkListMap = new HashMap<>();
            checkListMap.put("projectName", "检查项目：" + projectName);
            checkListMap.put("checkPart", "检查部位：" + p.getCheckPart());
            checkListMap.put("problemDes", "检查问题：" + p.getProblemDescription());
            checkListMap.put("suggestion", "处理建议：" + p.getSuggestion());
            temp++;
            if (temp != getPCD.size()) {
                pName4 += p.getpName4() + "、";
            } else {
                pName4 += p.getpName4();
            }
            checkList.add(checkListMap);
        }
        dataMap.put("checkList", checkList);
        dataMap.put("pName4", pName4);
        String maxRiskPoint = pointsCalculate.getMaxRiskPoint(getPCD);
        switch (maxRiskPoint) {
            case "1":
            case "提醒":
                dataMap.put("riskLevel", "4级隐患：符合要求");
            case "2":
                dataMap.put("riskLevel", "3级隐患：自查整改");
            case "3":
                dataMap.put("riskLevel", "2级隐患：限期整改");
            case "4":
                dataMap.put("riskLevel", "1级隐患：停工整改");
        }
        List<ContractCheckTask> sign = contractchecktaskMapper.getBaseData(checkId);
        if (sign.get(0).getSignPath() == null || sign.get(0).getSignPath().equals("")) {
            dataMap.put("jsUnitSign", MDoc.getImageStr("D:\\whutServer\\generatedCharts\\noPic.png"));
            dataMap.put("jlUnitSign", MDoc.getImageStr("D:\\whutServer\\generatedCharts\\noPic.png"));
            dataMap.put("sgUnitSign", MDoc.getImageStr("D:\\whutServer\\generatedCharts\\noPic.png"));
            //dataMap.put("jsUnitSign", MDoc.getImageStr("E:\\tencent_File\\1296928795\\FileRecv\\12.png"));
            //dataMap.put("jlUnitSign", MDoc.getImageStr("E:\\tencent_File\\1296928795\\FileRecv\\12.png"));
            //dataMap.put("sgUnitSign", MDoc.getImageStr("E:\\tencent_File\\1296928795\\FileRecv\\12.png"));
        } else {
            dataMap.put("jsUnitSign", MDoc.getImageStr(sign.get(0).getSignPath() + sign.get(0).getJsSign()));
            dataMap.put("jlUnitSign", MDoc.getImageStr(sign.get(0).getSignPath() + sign.get(0).getJlSign()));
            dataMap.put("sgUnitSign", MDoc.getImageStr(sign.get(0).getSignPath() + sign.get(0).getSgSign()));
            //dataMap.put("jsUnitSign", MDoc.getImageStr("E:\\tencent_File\\1296928795\\FileRecv\\123.png"));
            //dataMap.put("jlUnitSign", MDoc.getImageStr("E:\\tencent_File\\1296928795\\FileRecv\\123.png"));
            //dataMap.put("sgUnitSign", MDoc.getImageStr("E:\\tencent_File\\1296928795\\FileRecv\\123.png"));
        }
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        dataMap.put("date", df.format(t));

        Date date1 = new Date();
        DateFormat d1 = new SimpleDateFormat("yyyyMMddhhmmss");
        String fileName = d1.format(date1) + "spotCheckReport";
        MDoc mdoc = new MDoc();
        String path = FileUtil.getServerFolderPath();
        File f1 = new File(path, "doc");
        if (!f1.exists()) {
            f1.mkdirs();
        }
        mdoc.createDoc(dataMap, path + "\\doc\\" + header.get(0).getProjectName().replace('#', '号') + "建设工程施工安全监督抽查记录" + fileName + ".doc", "ftl\\spotCheck.ftl");
        //MDoc.docToDocx("D:\\whutServer\\apache-tomcat-8.5.41\\webapps\\ROOT\\doc\\" + header.get(0).getProjectName().replace('#','号')+"建设工程施工安全监督抽查记录"+fileName + ".doc", "D:\\whutServer\\apache-tomcat-8.5.41\\webapps\\ROOT\\doc\\"+ header.get(0).getProjectName().replace('#','号')+"建设工程施工安全监督抽查记录"+fileName + ".doc");
        String result = urlProperties.getAddress() + "/doc/" + header.get(0).getProjectName().replace('#', '号') + "建设工程施工安全监督抽查记录" + fileName + ".doc";
       /* MDoc mdoc = new MDoc();
        Date date1 = new Date();
        DateFormat d1 = new SimpleDateFormat("yyyyMMddhhmmss");
        String fileName = d1.format(date1)+"spotCheckReport";
        mdoc.createDoc(dataMap, "E:\\tencent_File\\1296928795\\FileRecv\\yirui" + fileName + ".doc", "ftl\\spotCheck.ftl");
        MDoc.docToDocx("E:\\tencent_File\\1296928795\\FileRecv\\yirui" + fileName + ".doc", "E:\\tencent_File\\1296928795\\FileRecv\\yirui" + fileName + ".doc");
        String result = "E:\\tencent_File\\1296928795\\FileRecv\\yirui" + fileName + ".doc";*/
        return result;
    }

    @Override
    public String patrolReport(int checkId, boolean isNew) throws UnsupportedEncodingException {
        ParSystemMapper parSystemMapper = isNew ? newPrefixSystemMapper : prefixParSystemMapper;
        ParProblemDescriptionMapper parProblemDescriptionMapper = isNew ? newproblemdescriptionMapper : problemDescriptionMapper;
        ParProblemCollectDetailMapper parProblemCollectDetailMapper = isNew ? newProblemCollectDetailMapper : problemCollectDetailMapper;
        return new PatrolReport(parSystemMapper,
                parProblemDescriptionMapper,
                parProblemCollectDetailMapper,
                this,
                mapperUtils,
                profiles).patrolReport(checkId, isNew);
    }


    /**
     * 香港置地安全报告/质量报告
     */
    @Override
    public String getMXTQreport(int checkId, int projectId, int reportType,boolean isNew) throws UnsupportedEncodingException{
        ParSystemMapper parSystemMapper =isNew ?newPrefixSystemMapper :prefixParSystemMapper;
        ParProblemDescriptionMapper parProblemDescriptionMapper = isNew ? newproblemdescriptionMapper : problemDescriptionMapper;
        ParProblemCollectDetailMapper parProblemCollectDetailMapper = isNew ? newProblemCollectDetailMapper : problemCollectDetailMapper;
        return new MXTQreport(parSystemMapper,
                        parProblemDescriptionMapper,
                        parProblemCollectDetailMapper,
                        this,
                        mapperUtils,
                        urlProperties,
                        profiles).getMXTQreport(checkId, projectId, reportType);

}
    /**
     * 可视化安全报告
     */
    @Override
    public String getVisualizationReport(int checkId, int projectId, boolean isNew) throws UnsupportedEncodingException {
        ParSystemMapper parSystemMapper =isNew ?newPrefixSystemMapper :prefixParSystemMapper;
        ParProblemDescriptionMapper parProblemDescriptionMapper = isNew ? newproblemdescriptionMapper : problemDescriptionMapper;
        ParProblemCollectDetailMapper parProblemCollectDetailMapper = isNew ? newProblemCollectDetailMapper : problemCollectDetailMapper;
        return new VisualizationReport(parSystemMapper,
                        parProblemDescriptionMapper,
                        parProblemCollectDetailMapper,
                        this,
                        mapperUtils,
                        urlProperties,
                        profiles).getVisualizationReport(checkId, projectId);
    }

    @Override
    public String getVisualizationReport2(int checkId, int projectId, boolean isNew) throws UnsupportedEncodingException {
        ParSystemMapper parSystemMapper =isNew ?newPrefixSystemMapper :prefixParSystemMapper;
        ParProblemDescriptionMapper parProblemDescriptionMapper = isNew ? newproblemdescriptionMapper : problemDescriptionMapper;
        ParProblemCollectDetailMapper parProblemCollectDetailMapper = isNew ? newProblemCollectDetailMapper : problemCollectDetailMapper;
        return new VisualizationReport2(parSystemMapper,
                        parProblemDescriptionMapper,
                        parProblemCollectDetailMapper,
                        this,
                        mapperUtils,
                        urlProperties,
                        profiles).getVisualizationReport2(checkId, projectId);
    }

    @Override
    public String constructionMulCheckReport(int checkId, int projectId, boolean isNew) throws UnsupportedEncodingException {
        ParSystemMapper parSystemMapper = isNew ? newPrefixSystemMapper : prefixParSystemMapper;
        ParProblemDescriptionMapper parProblemDescriptionMapper = isNew ? newproblemdescriptionMapper : problemDescriptionMapper;
        ParProblemCollectDetailMapper parProblemCollectDetailMapper = isNew ? newProblemCollectDetailMapper : problemCollectDetailMapper;
        return new ConstructionMulCheckReport(parSystemMapper,
                        parProblemDescriptionMapper,
                        parProblemCollectDetailMapper,
                        this,
                        mapperUtils,
                        urlProperties,
                        profiles).generateWord(checkId, projectId);
    }



    /**
     * @author: liukang
     * @Description: 市政设备专项评估报告，reportType=8255
     * @date: 2020/9/9 19:26
     * @param:
     * @return:
     */
    @Override
    public String cityEquipAssessReport(int checkId, int projectId, int reportType, boolean isNew) {
        ParSystemMapper parSystemMapper =isNew ?newPrefixSystemMapper :prefixParSystemMapper;
        ParProblemDescriptionMapper parProblemDescriptionMapper = isNew ? newproblemdescriptionMapper : problemDescriptionMapper;
        ParProblemCollectDetailMapper parProblemCollectDetailMapper = isNew ? newProblemCollectDetailMapper : problemCollectDetailMapper;
        return new CityEquipAssessReport(parSystemMapper,
                        parProblemDescriptionMapper,
                        parProblemCollectDetailMapper,
                        this,
                        mapperUtils,
                        urlProperties,
                        profiles).cityEquipAssessReport(checkId, projectId, reportType);
    }

    /**
     * @author: liukang
     * @Description: 房建设备专项评估报告，reportType=8256
     * @date: 2020/9/9 19:26
     * @param:
     * @return:
     */
    @Override
    public String houseEquipAssessReport(int checkId, int projectId, int reportType, boolean isNew) {
        ParSystemMapper parSystemMapper =isNew ?newPrefixSystemMapper :prefixParSystemMapper;
        ParProblemDescriptionMapper parProblemDescriptionMapper = isNew ? newproblemdescriptionMapper : problemDescriptionMapper;
        ParProblemCollectDetailMapper parProblemCollectDetailMapper = isNew ? newProblemCollectDetailMapper : problemCollectDetailMapper;
        return new HouseEquipAssessReport(parSystemMapper,
                        parProblemDescriptionMapper,
                        parProblemCollectDetailMapper,
                        this,
                        mapperUtils,
                        urlProperties,
                        profiles).houseEquipAssessReport(checkId, projectId, reportType);
    }

    //根据分项权重和权重和算出实际权重，并输出正确的格式
    public String calculatePercent(Integer singleWeight, Integer totalWeight) {

        //要用float
        float weight = (float) 100 * singleWeight / totalWeight;
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        String res = decimalFormat.format(weight);

        return res + "%";
    }

    //根据数据结果和文件名称生成报告，返回报告地址
    private String generateReport(Map dataMap, String reportName, String ftlName) {
        MDoc mdoc = new MDoc();
        String path = FileUtil.getServerFolderPath();
        File f1 = new File(path, "doc");
        if (!f1.exists()) {
            f1.mkdirs();
        }

        //报告本地测试使用
        /*String localReportPath = "E:\\tencent_File\\1296928795\\FileRecv\\yirui\\";
        try {
            mdoc.createDoc(dataMap, localReportPath + reportName + ".doc", "ftl\\"+ ftlName +".ftl");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        MDoc.docToDocx(localReportPath + reportName + ".doc", localReportPath + reportName + ".doc");
        String result = localReportPath + reportName + ".doc";*/

        //报告在服务器使用
        String tomcatDocPath = "D:\\whutServer\\apache-tomcat-8.5.41\\webapps\\ROOT\\doc\\";
        try {
            mdoc.createDoc(dataMap, path + "\\doc\\" + reportName + ".doc", "ftl\\" + ftlName + ".ftl");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //MDoc.docToDocx(tomcatDocPath + reportName + ".doc", tomcatDocPath + reportName + ".doc");
        String result = urlProperties.getAddress() + "/doc/" + reportName + ".doc";

        return result;
    }


    public int calculateAllFourthProblem(int checkId, JSONArray secondIdInfoArray, boolean isNew) {
        int allFourthProblem = 0;
        int temp = 0;
        for (int i = 0; i < secondIdInfoArray.size(); i++) {
            int secondId = secondIdInfoArray.getIntValue(i);
            temp = isNew ? newProblemCollectDetailMapper.countProblemBySecondId(checkId, secondId) :
                    problemCollectDetailMapper.countProblemBySecondId(checkId, secondId);
            allFourthProblem += temp;
        }
        return allFourthProblem;
    }

    public double calculateAllWeight4Func(int checkId, JSONObject part2InnerObject, Integer taskId, boolean isNew) {
        double allweight4 = 0;
        List<ProblemCollectDetail> countFourthWeight = isNew ? newProblemCollectDetailMapper.getAllFourthInfoMXTQ(checkId, part2InnerObject.getIntValue("thirdId")) :
                problemCollectDetailMapper.getAllFourthInfoMXTQ(checkId, part2InnerObject.getIntValue("thirdId"));
        for (int v = 0; v < countFourthWeight.size(); v++) {
            double Tweight4 = 0;
            int fourthId = countFourthWeight.get(v).getFourthId();
            //更改取权重的表
            String newWeight4 = editableweightpsMapper.getWeightByNumber(fourthId, taskId);
            if (StringUtils.isNotBlank(newWeight4)) {
                Tweight4 = pointsCalculate.getPercentInstance(newWeight4);
            } else {
                String trueweight4 = isNew ? newPrefixSystemMapper.getWeight3ByThirdId(fourthId) :
                        prefixParSystemMapper.getWeight3ByThirdId(fourthId);
                Tweight4 = pointsCalculate.getPercentInstance(trueweight4);
            }
            allweight4 += Tweight4;
        }
        return allweight4;
    }

    public String getCheckItemPointAndUpdateAllPointSave(int checkId, int part2FourthId, int projectId, double checkItemPoint, DecimalFormat df, boolean isNew) {
        List<ProblemCollectDetail> checkItemCalcuList = isNew? newProblemCollectDetailMapper.getAllFourthInfo(checkId, part2FourthId):problemCollectDetailMapper.getAllFourthInfo(checkId, part2FourthId);
        String maxFourthRiskPoint = pointsCalculate.getMaxRiskPoint(checkItemCalcuList);
        int maxFourthRiskPointNum = isNew? newProblemCollectDetailMapper.getRiskPointCount(checkId, part2FourthId, maxFourthRiskPoint):problemCollectDetailMapper.getRiskPointCount(checkId, part2FourthId, maxFourthRiskPoint);
        double limitFourhPoint = Double.parseDouble((pointlimitMapper.getLimitPointByInfo(String.valueOf(maxFourthRiskPointNum), maxFourthRiskPoint)) == null ? "100" : pointlimitMapper.getLimitPointByInfo(String.valueOf(maxFourthRiskPointNum), maxFourthRiskPoint));
        if (checkItemPoint > limitFourhPoint) {
            checkItemPoint = limitFourhPoint;
        }
        String s = df.format(checkItemPoint);
        int allPointSaveFourthPointCount = allpointsaveMapper.getAllPointCountByCheckId(checkId, part2FourthId);
        if (allPointSaveFourthPointCount != 0) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
            Date date1 = new Date(System.currentTimeMillis());
            String lastEditTime = formatter.format(date1);
            allpointsaveMapper.updateAllPoint(checkId, s, part2FourthId, lastEditTime);
        } else {
            Allpointsave allpointsave = new Allpointsave();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
            Date date1 = new Date(System.currentTimeMillis());
            allpointsave.setNewCreateTime(formatter.format(date1));
            allpointsave.setLastEditTime(formatter.format(date1));
            allpointsave.setProjectId(projectId);
            allpointsave.setCheckId(checkId);
            allpointsave.setNumber(part2FourthId);
            allpointsave.setPoint(s);
            allpointsaveMapper.insert(allpointsave);
        }
        return s;
    }

    public double calculateNoProblemPointFunc(int checkId, JSONObject part2InnerObject, boolean isNew) {
        double noProblemPoint = 0;
        List<Object> noProblemSixthIdList = uncheckeditemsMapper.getNoProblemSixthId(checkId, part2InnerObject.getIntValue("fourthId"));
        String noProblemSixthIdInfo = JSON.toJSONString(noProblemSixthIdList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
        JSONArray noProblemSixthArray = JSONArray.parseArray(noProblemSixthIdInfo);
        for (int m = 0; m < noProblemSixthArray.size(); m++) {
            int noProblemSixthId = noProblemSixthArray.getIntValue(m);
            double noProblem = Double.parseDouble(isNew ? newPrefixSystemMapper.getPoint4ByPoint4Id(noProblemSixthId)
                    : prefixParSystemMapper.getPoint4ByPoint4Id(noProblemSixthId));
            noProblemPoint += noProblem;
        }
        return noProblemPoint;
    }

    public String getPart2InnerListweight4(int checkId, int part2ThirdId, double weight3, double weight4, double allweight4, boolean isNew) {
        //int countFourthId=prefixParSystemMapper.getCountFourth(part2ThirdId);
        List<Object> fourthCountList = isNew ? newProblemCollectDetailMapper.getFourthCountList(checkId, part2ThirdId):problemCollectDetailMapper.getFourthCountList(checkId, part2ThirdId);
        String fourthCountInfo = JSON.toJSONString(fourthCountList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
        JSONArray fourthCountInfoArray = JSONArray.parseArray(fourthCountInfo);
        int countFourthId = fourthCountInfoArray.size();
        return pointsCalculate.double2ToPercent(weight3, allweight4 / weight4);
    }

    public List<Double> calculatePoint6Func(JSONArray sixthPointsArray, int checkId, boolean isNew) {
        double calculatePoint66 = 0;
        double calculatePoint6 = 0;
        double calculateTruePoint = 0;
        for (int y = 0; y < sixthPointsArray.size(); y++) {
            JSONObject sixPointObject = sixthPointsArray.getJSONObject(y);
            int deductSixthId = sixPointObject.getIntValue("sixthId");
            System.out.println("sixId:" + deductSixthId);
            float deductPointsSumFloat = isNew ? newProblemCollectDetailMapper.getdeductSum(checkId, deductSixthId) : problemCollectDetailMapper.getdeductSum(checkId, deductSixthId);
            double deductPointsSum = Double.valueOf(String.valueOf(deductPointsSumFloat));
            double truePoint = Double.parseDouble(sixPointObject.getString("point6"));
            System.out.println("各类point:" + deductPointsSum + " " + truePoint);
            if (truePoint <= deductPointsSum) {
                calculatePoint66 = 0;
            } else {
                calculatePoint66 = truePoint - deductPointsSum;
            }
            calculateTruePoint += truePoint;  //体系分数
            calculatePoint6 += calculatePoint66;  //得分总和
        }
        List<Double> calculatePointList = new ArrayList<>();
        calculatePointList.add(calculateTruePoint);
        calculatePointList.add(calculatePoint6);
        System.out.println("计算point6:" + calculatePointList);
        return calculatePointList;
    }

    /**
     * @author： wenyihan
     * @description：设备报告
     * @date： 20:22 2020/11/21
     * @param： [checkId, projectId]
     * @return： java.lang.String
     */
    @Override
    public String equipReport(int checkId, int projectId, boolean isNew) {
        ParSystemMapper parSystemMapper = isNew ? newPrefixSystemMapper : prefixParSystemMapper;
        ParProblemDescriptionMapper parProblemDescriptionMapper = isNew ? newproblemdescriptionMapper : problemDescriptionMapper;
        ParProblemCollectDetailMapper parProblemCollectDetailMapper = isNew ? newProblemCollectDetailMapper : problemCollectDetailMapper;
        return new EquipReport(parSystemMapper,
                        parProblemDescriptionMapper,
                        parProblemCollectDetailMapper,
                        this,
                        mapperUtils).equipReport(checkId, projectId);

    }

    /**
     * @author： wenyihan
     * @description：扣分范围
     * @date： 1:06 2020/11/24
     * @param： [deductPoint]
     * @return： java.lang.String
     */
    public String deductPointRange(String deductPoint) {
        List<String> list = Arrays.asList(deductPoint.split(";"));
        List<Integer> listInteger = list.stream()
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        if (listInteger.size() == 1) {
            return deductPoint;
        } else {
            List<Integer> sortedList = listInteger.stream()
                    .sorted()
                    .collect(Collectors.toList());
            if (sortedList.get(0).equals(sortedList.get(sortedList.size() - 1))) {
                return sortedList.get(0) + "";
            } else {
                String deductPointRange = sortedList.get(0) + "~" + sortedList.get(list.size() - 1);
                return deductPointRange;
            }
        }
    }

    /**
     * @author： wenyihan
     * @description：判断值是否为空
     * @date： 15:21 2020/11/22
     * @param： [t]
     * @return： boolean
     */
    public <T> boolean configIsNull(T t) {
        if (t != null) {
            return true;
        }
        return false;
    }

    /**
     * @author： wenyihan
     * @description：综合巡查报告单
     * @date： 18:21 2020/11/28
     * @param： [checkId, projectId]
     * @return： java.lang.String
     */
    @Override
    public String comperhensiveInspectionReport(int checkId, int projectId, boolean isNew) {
        ParSystemMapper parSystemMapper = isNew? newPrefixSystemMapper : prefixParSystemMapper;
        ParProblemCollectDetailMapper parProblemCollectDetailMapper = isNew? newProblemCollectDetailMapper : problemCollectDetailMapper;
        ParProblemDescriptionMapper parProblemDescriptionMapper = isNew? newproblemdescriptionMapper : problemDescriptionMapper;

        return new ComperhensiveInspectionReport(parSystemMapper,
                        parProblemDescriptionMapper,
                        parProblemCollectDetailMapper,
                        this,
                        mapperUtils,
                        urlProperties,
                        profiles).comperhensiveInspectionReport(checkId, projectId);
    }
    /**
     * @author  wangqirui
     * @create  2021/7/17 上午 11:26
     * @desc 综合检查风险报告
     **/
    @Override
    public String ComprehensiveInspectionRiskReport(int projectId, int checkId, boolean isNew) throws UnsupportedEncodingException {
        ParSystemMapper parSystemMapper = isNew ? newPrefixSystemMapper : prefixParSystemMapper;
        ParProblemDescriptionMapper parProblemDescriptionMapper = isNew ? newproblemdescriptionMapper : problemDescriptionMapper;
        ParProblemCollectDetailMapper parProblemCollectDetailMapper = isNew ? newProblemCollectDetailMapper : problemCollectDetailMapper;
        return new ComprehensiveInspectionRiskReport(parSystemMapper,
                parProblemDescriptionMapper,
                parProblemCollectDetailMapper,
                this,
                mapperUtils,
                urlProperties,
                profiles).generateReport(checkId, projectId);
    }
        /**
         * @author wangqirui
         * @create 2021/3/2 下午 3:33
         * @desc 第三方设备评估报告
         **/
    @Override
    public String generate3rdPartyRiskReport(int projectId, int checkId, boolean isNew) throws UnsupportedEncodingException {
        RiskPoint riskPoint = new RiskPoint();
        Map<String, Object> dataMap = new HashMap<String, Object>(100, 0.75f);
        //初始化主题
        initWordTheme();
        //初始化时间
        initWordDate(dataMap);
        //工程概况初始
        initProjectProfiles(dataMap);
        //第一部分工程概况部分，来自ctp的工程信息
        initProjectSummaryFirstPart(projectId, dataMap);
        //工程概况部分，来自设备信息表的设备信息部分
        initProjectMachineInfo(dataMap, projectId);
        //第一部分，（二）分项评估结果
        new SubAssessResult(this, equipService, checkId, riskPoint, dataMap).initSubAssessResult();
        //第一部分，（三）各个专业问题的分布情况
        initProblemDistribution(checkId, dataMap, riskPoint);
        //第一部分，三.检查问题综述
        initCheckProblemSummary(checkId, dataMap);

        initRiskPoint(checkId, riskPoint, dataMap);
        //创建隐患分布饼图
        createPieChart(checkId, riskPoint, dataMap);
        //创建隐患分布直方图
        createBarChart(checkId, riskPoint, dataMap);

        saveImageStr(dataMap);
        //第二部分，各部分工程检查情况
        initPartProjectCheckCondition(checkId, dataMap, riskPoint);
        //根据dataMap生成报告
        return ReportCommonFunc.generateReport(dataMap, getReportName(dataMap), "thirdPartyRiskReport");

    }

    public String getReportName(Map<String, Object> dataMap) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddhhmmss");
        String fileNameTime = dateTimeFormatter.format(LocalDateTime.now());
        return HbyrStringUtils.wipeOffSymbol(String.valueOf(dataMap.get("projectName")), '#') + "第三方设备风险评估报告" + fileNameTime;
    }

    public void initPartProjectCheckCondition(int checkId, Map<String, Object> dataMap, RiskPoint riskPoint) {
        List<Object> section2List = new ArrayList<Object>();
        for (Integer pName1 : getpName1Info(checkId)) {
            Map<String, Object> section2Name1Map = new HashMap<String, Object>();
            List<Object> section2name1List = new ArrayList<Object>();
            section2Name1Map.put("section2pName1", getSection2pName1(pName1));
            for (Integer pName4Info : getSection2Name4InfoList(checkId, pName1)) {
                section2name1List.add(getSection2Name4Map(checkId, pName1, pName4Info));
            }
            section2Name1Map.put("section2Name1List", section2name1List);
            section2List.add(section2Name1Map);
        }
        dataMap.put("section2List", section2List);

        createConstructionPieChart(checkId, riskPoint, dataMap);

        createConstructionBarChart(checkId, dataMap);

        putImageStr(dataMap, "pic6", "pieChart.png");

        putImageStr(dataMap, "pic7", "barChart.png");
    }

    private void createConstructionBarChart(int checkId, Map<String, Object> dataMap) {
        try {
            JFreeChart barChart = ChartFactory.createBarChart("现场施工问题分布直方图",
                    "",
                    "数量",
                    getDataSetBar(checkId),
                    PlotOrientation.VERTICAL,
                    true, true, false);
            CategoryPlot plot = (CategoryPlot) barChart.getPlot();
            plot.getRenderer().setSeriesPaint(0, new Color(5, 87, 232));
            BarRenderer barRenderer = (BarRenderer) plot.getRenderer();
            barRenderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
            barRenderer.setDefaultItemLabelsVisible(true);
            barRenderer.setItemLabelAnchorOffset(-20D);
            barRenderer.setMaximumBarWidth(0.2);
            CategoryAxis categoryAxis = plot.getDomainAxis();
            categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
            File barChartFile = new File(getImgFileStr(dataMap, "barChart.png"));
            ChartUtils.saveChartAsPNG(barChartFile, barChart, WIDTH, HEIGHT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createConstructionPieChart(int checkId, RiskPoint riskPoint, Map<String, Object> dataMap) {
        try {
            JFreeChart chart = ChartFactory.createPieChart("现场施工问题分布饼图", getDataSetPie(checkId, riskPoint.getAllRiskPoint()), true, true, false);
            final PiePlot plot = (PiePlot) chart.getPlot();
            plot.setStartAngle(270);
            plot.setForegroundAlpha(0.90f);
            plot.setInteriorGap(0.02);
            chart.getLegend().setVisible(false);
            File pieChart = new File(getImgFileStr(dataMap, "pieChart.png"));
            ChartUtils.saveChartAsPNG(pieChart, chart, WIDTH, HEIGHT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Map<String, Object> getSection2Name4Map(int checkId, Integer firstId, Integer pName4Info) {
        Map<String, Object> section2Name4Map = new HashMap<String, Object>();
        section2Name4Map.put("section2pName4", newPrefixSystemMapper.getName4ByName4Id(pName4Info));
        section2Name4Map.put("section2Name4List", getSection2Name4List(checkId, firstId, pName4Info));
        return section2Name4Map;
    }

    private List<Object> getSection2Name4List(int checkId, Integer firstId, Integer pName4Info) {
        List<Object> section2Name4List = new ArrayList<Object>();
        final List<ProblemCollectDetail> section2Name6InfoList = getSection2Name6InfoList(checkId, firstId, pName4Info);
        for (int i = 0; i < section2Name6InfoList.size(); i++) {
            section2Name4List.add(getSection2Name6Map(i, section2Name6InfoList));
        }
        return section2Name4List;
    }

    private Map<String, Object> getSection2Name6Map(int i, List<ProblemCollectDetail> section2Name6InfoList) {
        Map<String, Object> section2Name6Map = new HashMap<String, Object>();
        List<Object> picList = new ArrayList<Object>();
        final ProblemCollectDetail section2Name6Info = section2Name6InfoList.get(i);
        section2Name6Map.put("section2pName6No", i + 1);
        section2Name6Map.put("section2pName6", section2Name6Info.getpName6());
        section2Name6Map.put("section2pName5", section2Name6Info.getpName5());
        String problemListRiskPoint = "";
        switch (section2Name6Info.getRiskPoint()) {
            case "提醒":
                problemListRiskPoint = "提醒";
                break;
            case "1":
                problemListRiskPoint = "四级隐患";
                break;
            case "2":
                problemListRiskPoint = "三级隐患";
                break;
            case "3":
                problemListRiskPoint = "二级隐患";
                break;
            case "4":
                problemListRiskPoint = "一级隐患";
                break;
            default:
                problemListRiskPoint = "";
                break;
        }
        section2Name6Map.put("section2RiskLevel", problemListRiskPoint);
        section2Name6Map.put("section2CheckPart", section2Name6Info.getCheckPart());
        section2Name6Map.put("section2ProblemNum", section2Name6Info.getProblemQua());
        if ("N".equals(section2Name6Info.getIsRemark())) {
            section2Name6Map.put("section2problemDescription", section2Name6Info.getProblemDescription());
        } else {
            section2Name6Map.put("section2problemDescription", section2Name6Info.getRemark());
        }
        section2Name6Map.put("section2normsProvison", section2Name6Info.getNormsProvison());
        section2Name6Map.put("section2suggestion", section2Name6Info.getSuggestion());
        JSONArray ja = getPicArray(section2Name6Info);
        if (ja.size() == 0) {
            picList.add(MDoc.getImageStr(imgFile.getPath() + "noPic.png"));
        } else {
            for (Object jsonValues : getPicArray(section2Name6Info)) {
                String s = "";
                if ("prod".equals(profiles.getActives())) {
                    s = MDoc.getImageStr(section2Name6Info.getPicPath() + jsonValues.toString());
                }
                picList.add(s);
            }
        }
        section2Name6Map.put("picList", picList);
        return section2Name6Map;
    }

    private JSONArray getPicArray(ProblemCollectDetail section2Name6Info) {
        return JSONArray.parseArray(section2Name6Info.getPicName());
    }

    private List<ProblemCollectDetail> getSection2Name6InfoList(int checkId, Integer firstId, Integer section2Name4Info) {
        return newProblemCollectDetailMapper.getAllName6InfoByName4(checkId, section2Name4Info, getSection2Name1(firstId));
    }

    private List<Integer> getSection2Name4InfoList(int checkId, Integer problemCollectDetail) {
        return newProblemCollectDetailMapper.getAllName4ByName1(checkId, getSection2Name1(problemCollectDetail));
    }

    private String getSection2pName1(Integer index) {
        String section2pName1 = "";
        String section2Name1 = getSection2Name1(index);
        if ("新安全检查".equals(section2Name1)) {
            section2pName1 = "安全问题";
        } else if ("新质量检查".equals(section2Name1)) {
            section2pName1 = "质量问题";
        } else if ("新管理行为".equals(section2Name1)) {
            section2pName1 = "管理体系及管理动作";
        } else if ("新设备检查".equals(section2Name1)) {
            section2pName1 = "设备检查问题";
        }
        return section2pName1;
    }

    private String getSection2Name1(Integer index) {
        return newPrefixSystemMapper.getName4ByName4Id(index);
    }

    public void saveImageStr(Map<String, Object> dataMap) {
        putImageStr(dataMap, "pic8", "RiskPieChart.png");
        putImageStr(dataMap, "pic9", "RiskBarChart.png");
    }

    private void putImageStr(Map<String, Object> dataMap, String key, String imgStr) {
        if (isFoundImageStr(dataMap, imgStr)) {
            dataMap.put(key, MDoc.getImageStr(getImgFileStr(dataMap, imgStr)));
        } else {
            dataMap.put(key, "");
        }
    }

    private boolean isFoundImageStr(Map<String, Object> dataMap, String imgStr) {
        return MDoc.isFoundImageStr(getImgFileStr(dataMap, imgStr));
    }

    private String getImgFileStr(Map<String, Object> dataMap, String imgStr) {
        return imgFile.getPath() + dataMap.get("fileDate") + imgStr;
    }

    public void createBarChart(int checkId, RiskPoint riskPoint, Map<String, Object> dataMap) {
        try {
            JFreeChart barChart = ChartFactory.createBarChart("隐患分布直方图",
                    "",
                    "数量",
                    getDataSetRiskBar(checkId, riskPoint),
                    PlotOrientation.VERTICAL,
                    true, true, false);
            CategoryPlot plot = (CategoryPlot) barChart.getPlot();
            BarRenderer barRenderer = (BarRenderer) plot.getRenderer();
            plot.getRenderer().setSeriesPaint(0, new Color(49, 95, 232));
            plot.getRenderer().setSeriesPaint(1, new Color(232, 232, 49));
            plot.getRenderer().setSeriesPaint(2, new Color(240, 117, 60));
            plot.getRenderer().setSeriesPaint(3, new Color(232, 36, 18));
            barRenderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
            barRenderer.setDefaultItemLabelsVisible(true);
            barRenderer.setItemLabelAnchorOffset(-20D);
            ChartUtils.saveChartAsPNG(getImgFile(dataMap, "RiskBarChart.png"), barChart, WIDTH, HEIGHT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void createPieChart(int checkId, RiskPoint riskPoint, Map<String, Object> dataMap) {
        try {
            JFreeChart chart = ChartFactory.createPieChart("隐患分布饼图", getDataSetRiskPie(checkId, riskPoint), true, true, false);
            final PiePlot plot = (PiePlot) chart.getPlot();
            chart.getLegend().setVisible(false);

            plot.setStartAngle(0);
            plot.setForegroundAlpha(0.90f);
            plot.setInteriorGap(0.02);
            plot.setSectionPaint("四级隐患" + ":" + getTxAndOnePercent(checkId, riskPoint), new Color(49, 95, 232));
            plot.setSectionPaint("三级隐患" + ":" + getTwoPercent(riskPoint), new Color(232, 232, 49));
            plot.setSectionPaint("二级隐患" + ":" + getThreePercent(riskPoint), new Color(240, 117, 60));
            plot.setSectionPaint("一级隐患" + ":" + getFourPercent(riskPoint), new Color(232, 36, 18));
            ChartUtils.saveChartAsPNG(getImgFile(dataMap, "RiskPieChart.png"), chart, WIDTH, HEIGHT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private File getImgFile(Map<String, Object> dataMap, String imgStr) {
        return new File(imgFile.getPath() + dataMap.get("fileName") + imgStr);
    }

    private DefaultCategoryDataset getDataSetRiskBar(int checkId, RiskPoint riskPoint) {
        DefaultCategoryDataset datasetRiskBar = new DefaultCategoryDataset();
        String riskBar = "隐患等级情况统计";
        datasetRiskBar.addValue(getTxNum(checkId) + riskPoint.getRiskPoint1(), "四级隐患", riskBar);
        datasetRiskBar.addValue(riskPoint.getRiskPoint2(), "三级隐患", riskBar);
        datasetRiskBar.addValue(riskPoint.getRiskPoint3(), "二级隐患", riskBar);
        datasetRiskBar.addValue(riskPoint.getRiskPoint4(), "一级隐患", riskBar);
        return datasetRiskBar;
    }

    private DefaultPieDataset getDataSetRiskPie(int checkId, RiskPoint riskPoint) {
        DefaultPieDataset datasetRiskPie = new DefaultPieDataset();
        datasetRiskPie.setValue("四级隐患" + ":" + getTxAndOnePercent(checkId, riskPoint), new Double(getTxNum(checkId) + riskPoint.getRiskPoint1()));
        datasetRiskPie.setValue("三级隐患" + ":" + getTwoPercent(riskPoint), new Double(riskPoint.getRiskPoint2()));
        datasetRiskPie.setValue("二级隐患" + ":" + getThreePercent(riskPoint), new Double(riskPoint.getRiskPoint3()));
        datasetRiskPie.setValue("一级隐患" + ":" + getFourPercent(riskPoint), new Double(riskPoint.getRiskPoint4()));
        return datasetRiskPie;
    }

    private String getTxAndOnePercent(int checkId, RiskPoint riskPoint) {
        return pointsCalculate.caculateToPercent(getTxNum(checkId) + riskPoint.getRiskPoint1(), riskPoint.getAllRiskPoint());
    }

    private String getFourPercent(RiskPoint riskPoint) {
        return pointsCalculate.caculateToPercent(riskPoint.getRiskPoint4(), riskPoint.getAllRiskPoint());
    }

    private String getThreePercent(RiskPoint riskPoint) {
        return pointsCalculate.caculateToPercent(riskPoint.getRiskPoint3(), riskPoint.getAllRiskPoint());
    }

    private String getTwoPercent(RiskPoint riskPoint) {
        return pointsCalculate.caculateToPercent(riskPoint.getRiskPoint2(), riskPoint.getAllRiskPoint());
    }

    private String getOnePercent(RiskPoint riskPoint) {
        return pointsCalculate.caculateToPercent(riskPoint.getRiskPoint1(), riskPoint.getAllRiskPoint());
    }

    private String getTxPercent(int checkId, RiskPoint riskPoint) {
        return pointsCalculate.caculateToPercent(getTxNum(checkId), riskPoint.getAllRiskPoint());
    }

    public void initRiskPoint(int checkId, RiskPoint riskPoint, Map<String, Object> dataMap) {
        dataMap.put("txNum", getTxNum(checkId));
        dataMap.put("oneNum", riskPoint.getRiskPoint1());
        dataMap.put("twoNum", riskPoint.getRiskPoint2());
        dataMap.put("threeNum", riskPoint.getRiskPoint3());
        dataMap.put("fourNum", riskPoint.getRiskPoint4());

        dataMap.put("txPercent", getTxPercent(checkId, riskPoint));
        dataMap.put("onePercent", getOnePercent(riskPoint));
        dataMap.put("twoPercent", getTwoPercent(riskPoint));
        dataMap.put("threePercent", getThreePercent(riskPoint));
        dataMap.put("fourPercent", getFourPercent(riskPoint));
    }

    private int getTxNum(int checkId) {
        return newProblemCollectDetailMapper.getAllRiskPointCountByType(checkId, "提醒");
    }

    public void initCheckProblemSummary(int checkId, Map<String, Object> dataMap) {
        for (Integer firstId : getpName1Info(checkId)) {
            dataMap.put("partProblemName1List", getPartProblemName1List(checkId, firstId));
        }
    }


    private List<Object> getPartProblemName1List(int checkId, Integer firstId) {
        List<Object> partProblemName1List = new ArrayList<Object>();
        for (Integer problemName4Num : getProbelmName4List(checkId, firstId)) {
            for (ProblemCollectDetail partProblemDetail : getPartProblemDetailList(checkId, problemName4Num)) {
                Map<String, Object> partProblemName1Map = new HashMap<String, Object>();
                if (isRemarkEquals(partProblemDetail)) {
                    partProblemName1Map.put("problemDescription", partProblemDetail.getProblemDescription());
                } else {
                    partProblemName1Map.put("problemDescription", partProblemDetail.getRemark());
                }
                String riskPoint1 = "";
                switch (partProblemDetail.getRiskPoint()) {
                    case "提醒":
                        riskPoint1 = "四级隐患";
                        break;
                    case "1":
                        riskPoint1 = "四级隐患";
                        break;
                    case "2":
                        riskPoint1 = "三级隐患";
                        break;
                    case "3":
                        riskPoint1 = "二级隐患";
                        break;
                    case "4":
                        riskPoint1 = "一级隐患";
                        break;
                    default:
                        riskPoint1 = "";
                        break;
                }
                partProblemName1Map.put("riskPoint", riskPoint1);
                partProblemName1Map.put("name4", newPrefixSystemMapper.getName4ByName4Id(problemName4Num));
                partProblemName1List.add(partProblemName1Map);
            }
        }
        return partProblemName1List;
    }

    private boolean isRemarkEquals(ProblemCollectDetail partProblemDetail) {
        return "N".equals(partProblemDetail.getIsRemark());
    }

    private List<ProblemCollectDetail> getPartProblemDetailList(int checkId, Integer problemName4Num) {
        return newProblemCollectDetailMapper.getAllFourthInfo(checkId, problemName4Num);
    }

    private List<Integer> getProbelmName4List(int checkId, Integer firstId) {
        return newProblemCollectDetailMapper.getAllName4ByName1(checkId, getPName1(firstId));
    }

    private String getPName1(Integer firstId) {
        return newPrefixSystemMapper.getName4ByName4Id(firstId);
    }

    public void initProblemDistribution(int checkId, Map<String, Object> dataMap, RiskPoint riskPoint) {
        dataMap.put("allProblemNum", riskPoint.getAllRiskPoint());
        dataMap.put("part3List", getPart3List(checkId, riskPoint.getAllRiskPoint()));
    }

    private DefaultCategoryDataset getDataSetBar(int checkId) {
        DefaultCategoryDataset datasetBar = new DefaultCategoryDataset();
        for (Integer pName4Id : getpName4Info(checkId)) {
            datasetBar.addValue(getName4Num(checkId, pName4Id), "各检查分项", getPName4(pName4Id));
        }
        return datasetBar;
    }

    private DefaultPieDataset getDataSetPie(int checkId, Integer allRiskPoint) {
        DefaultPieDataset datasetPie = new DefaultPieDataset();
        for (Integer pName4Id : getpName4Info(checkId)) {
            final int name4Num = getName4Num(checkId, pName4Id);
            final String percent = pointsCalculate.caculateToPercent(name4Num, allRiskPoint);
            datasetPie.setValue(getPName4(pName4Id) + ":" + percent, new Double(name4Num));
        }
        return datasetPie;
    }

    private List<Object> getPart3List(int checkId, Integer allRiskPoint) {
        List<Object> part3List = new ArrayList<Object>();
        for (Integer pName4Id : getpName4Info(checkId)) {
            Map<String, Object> part3Map = new HashMap<String, Object>();
            final int name4Num = getName4Num(checkId, pName4Id);
            final String percent = pointsCalculate.caculateToPercent(name4Num, allRiskPoint);
            part3Map.put("No", pName4Id + 1);
            part3Map.put("name4", getPName4(pName4Id));
            part3Map.put("problemNum", name4Num);
            part3Map.put("percent", percent);
            part3List.add(part3Map);
        }
        return part3List;
    }

    private int getName4Num(int checkId, Integer pName4Id) {
        int name4Num = newProblemCollectDetailMapper.countName4(pName4Id, checkId);
        return name4Num;
    }

    private String getPName4(Integer pName4Id) {
        return newPrefixSystemMapper.getName4ByName4Id(pName4Id);
    }

    private List<Integer> getpName4Info(int checkId) {
        return newProblemCollectDetailMapper.getAllName4(checkId);
    }

    private List<Integer> getpName1Info(int checkId) {
        return newProblemCollectDetailMapper.getAllName1Id(checkId);
    }

    private double getAllWeight1(List<ProblemCollectDetail> pName1Info) {
        double allWeight1 = 0;
        for (ProblemCollectDetail problemCollectDetail : pName1Info) {
            allWeight1 += getTweight1(problemCollectDetail);
        }
        return allWeight1;
    }

    private double getTweight1(ProblemCollectDetail problemCollectDetail) {
        double Tweight1;
        Tweight1 = pointsCalculate.getPercentInstance(getWeight1(problemCollectDetail));
        return Tweight1;
    }

    private String getWeight1(ProblemCollectDetail problemCollectDetail) {
        return newPrefixSystemMapper.getWeight1ByName1(newPrefixSystemMapper.getName4ByName4Id(problemCollectDetail.getMkey()));
    }


    public List<Map<String, Object>> getP6ProblemList(List<ProblemCollectDetail> pcdInfoBy4th) {
        List<Map<String, Object>> p6ProblemList = new ArrayList<>();
        for (ProblemCollectDetail problemCollectDetail : pcdInfoBy4th) {
            Map<String, Object> p6ProblemMap = new HashMap<>();
            p6ProblemMap.put("checkPart", problemCollectDetail.getCheckPart());
            String riskPoint1 = "";
            switch (problemCollectDetail.getRiskPoint()) {
                case "提醒":
                    riskPoint1 = "四级隐患";
                    break;
                case "1":
                    riskPoint1 = "四级隐患";
                    break;
                case "2":
                    riskPoint1 = "三级隐患";
                    break;
                case "3":
                    riskPoint1 = "二级隐患";
                    break;
                case "4":
                    riskPoint1 = "一级隐患";
                    break;
                default:
                    riskPoint1 = "";
                    break;
            }
//            p6ProblemMap.put("newRiskPoint", riskPoint1);
            p6ProblemMap.put("riskPoint", problemCollectDetail.getRiskPoint());
            if (isRemarkEquals(problemCollectDetail)) {
                p6ProblemMap.put("problemDescription", problemCollectDetail.getProblemDescription());
            } else {
                p6ProblemMap.put("problemDescription", problemCollectDetail.getRemark());
            }
            p6ProblemList.add(p6ProblemMap);
        }
        return p6ProblemList;
    }

    public List<ProblemCollectDetail> getPcdInfoListBy4th(int checkId, Object fourth) {
        return newProblemCollectDetailMapper.getAllFourthInfo(checkId, Integer.parseInt(fourth.toString()));
    }

    public List<Object> getFouthIdList(int checkId, Integer thirdId) {
        List<ProblemCollectDetail> pcdInfoBy3rd = this.getPCDInfoList(checkId, thirdId);
        return newProblemCollectDetailMapper.
                getFourthId(checkId, pcdInfoBy3rd.get(0).getpName1(), pcdInfoBy3rd.get(0).getSecondId(), thirdId);
    }

    public List<ProblemCollectDetail> getPCDInfoList(int checkId, Integer thirdId) {
        return newProblemCollectDetailMapper.selectAllInfoByThirdId(checkId, thirdId);
    }

    private String getMachineTypeByNum(Integer machineType) {
        if (machineType == null) {
            throw new NullPointerException("空指针异常");
        }
        return newPrefixSystemMapper.getName4ByName4Id(machineType);
    }

    // yyyy-mm-dd 转为年月日
    public static String getChinaDateFromString(String str) {
        try {
            if (str == null) {
                return getChinaCurrentDate();
            }
            str = str.trim();
            int year = 0;
            int month = 0;
            int day = 0;
            if (str == null || str.equals("null") || str.equals("")) {
                return getChinaCurrentDate();
            } else if (str.indexOf("年") > 0 || str.indexOf("月") > 0 || str.indexOf("日") > 0) {
                return str;
            } else {
                if (str.length() == 10 && (str.indexOf("-") > 0)) { //  add str.indexOf("-") > 0
                    year = Integer.parseInt(str.substring(0, 4));
                    month = Integer.parseInt(str.substring(5, 7));
                    day = Integer.parseInt(str.substring(8, 10));
                } else if (str.length() == 8) {
                    year = Integer.parseInt(str.substring(0, 4));
                    month = Integer.parseInt(str.substring(4, 6));
                    day = Integer.parseInt(str.substring(6, 8));
                } else if (str.length() == 6) {
                    year = Integer.parseInt(str.substring(0, 4));
                    month = Integer.parseInt(str.substring(4, 6));
                }
                if (day == 0)
                    str = year + "年" + month + "月";
                else
                    str = year + "年" + month + "月" + day + "日";
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return str;
    }

    public static String getChinaCurrentDate() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        String str_date = dateFormat.format(Calendar.getInstance().getTime());

        str_date = str_date.substring(0, 4) + "年" + str_date.substring(4, 6) + "月" +

                str_date.substring(6, 8) + "日 ";

        return str_date;

    }

    @Override
    public String equipReport(int checkId, int projectId, String checkPart, int fourthId, String ftlName) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        ContractCheckTask cct = contractchecktaskMapper.selectByPrimaryKey(checkId);
        ContractTaskProject ctp = contractTaskProjectMapper.selectByPrimaryKey(projectId);
        dataMap.put("area", ctp.getArea());
        dataMap.put("projectName", cct.getProjectName());
        dataMap.put("checkPart", checkPart);
        String time = getChinaDateFromString(cct.getFinishTime());
        dataMap.put("finishTime", time);
        MachineInfo Mi = machineinfoMapper.getAllByProjectIdAndEquipNum(projectId, checkPart);
        dataMap.put("equipModel", Mi.getEquipModel());
        if (Mi.getRegistNum() == null) {
            dataMap.put("registNum", "//");
        } else {
            dataMap.put("registNum", Mi.getRegistNum());
        }
        if (Mi.getProductionUnit() == null) {
            dataMap.put("productionUnit", "//");
        } else {
            dataMap.put("productionUnit", Mi.getProductionUnit());
        }
        if (Mi.getEquipRegistNum() == null) {
            dataMap.put("equipRegistNum", "//");
        } else {
            dataMap.put("equipRegistNum", Mi.getEquipRegistNum());
        }
        if (Mi.getFactoryDate() == null) {
            dataMap.put("factoryDate", "//");
        } else {
            dataMap.put("factoryDate", Mi.getFactoryDate());
        }
        if (Mi.getFactoryNum() == null) {
            dataMap.put("factoryNum", "//");
        } else {
            dataMap.put("factoryNum", Mi.getFactoryNum());
        }
        if (Mi.getInstallRemoveUnit() == null) {
            dataMap.put("installRemoveUnit", "//");
        } else {
            dataMap.put("installRemoveUnit", Mi.getInstallRemoveUnit());
        }
        if (Mi.getUseHeight() == null) {
            dataMap.put("useHeight","//");
        }
        else {
            dataMap.put("useHeight",Mi.getUseHeight()+"米");
        }
        if (Mi.getFrameHeight() == null) {
            dataMap.put("frameHeight","//");
        }
        else {
            dataMap.put("frameHeight",Mi.getFrameHeight());
        }
        if (Mi.getDetectionUnit() == null) {
            dataMap.put("detectionUnit", "//");
        } else {
            dataMap.put("detectionUnit", Mi.getDetectionUnit());
        }
        if (Mi.getUseUnit() == null) {
            dataMap.put("useUnit", "//");
        } else {
            dataMap.put("useUnit", Mi.getUseUnit());
        }
        if (Mi.getEquipNum() == null) {
            dataMap.put("equipNum", "//");
        } else {
            dataMap.put("equipNum", Mi.getEquipNum());
        }
        List<ProblemCollectDetail> problemCollectDetails = newProblemCollectDetailMapper.getAllFourthInfo(checkId, fourthId);
        List<ProblemCollectDetail> ensureList = new ArrayList<ProblemCollectDetail>();
        List<ProblemCollectDetail> normalList = new ArrayList<ProblemCollectDetail>();
        for (ProblemCollectDetail pcd : problemCollectDetails) {
            if (pcd.getCheckPart().equals(checkPart)) {
                if (pcd.getpName5().equals("保证项目")) {
                    if(pcd.getRemark().length()==0){
                        pcd.setRemark(pcd.getProblemDescription());
                    }
                    ensureList.add(pcd);
                }
                if (pcd.getpName5().equals("一般项目")) {
                    if(pcd.getRemark().length()==0){
                        pcd.setRemark(pcd.getProblemDescription());
                    }
                    normalList.add(pcd);
                }
            }
        }
        for (int i = 0; i < ensureList.size(); i++) {
            ensureList.get(i).setMkey(i + 1);
        }
        for (int i = 0; i < normalList.size(); i++) {
            normalList.get(i).setMkey(i + 1);
        }
        dataMap.put("ensureList", ensureList);
        dataMap.put("normalList", normalList);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddhhmmss");
        String fileNameTime = dateTimeFormatter.format(LocalDateTime.now());
        String reportName = checkPart.replace("#","号") + "检查表(" + ctp.getArea() + ")" + fileNameTime;
        return ReportCommonFunc.generateReport(dataMap, reportName, ftlName);
    }

    @Override
    public String equipTowerReport(int checkId, int projectId, String checkPart, int fourthId) {
        String ftlName = "equipTower";
        return equipReport(checkId, projectId, checkPart, fourthId, ftlName);
    }

    //施工升降机检查表  和塔式表完全一致
    @Override
    public String constructionLifterReport(int checkId, int projectId, String checkPart, int fourthId) {
        return equipTowerReport(checkId, projectId, checkPart, fourthId);
    }

    //门式起重机检查表  多一个为空的跨度，可以忽略
    @Override
    public String gantryCraneReport(int checkId, int projectId, String checkPart, int fourthId) {
        String ftlName = "gantryCrane";
        return equipReport(checkId, projectId, checkPart, fourthId, ftlName);
    }

    //流式起重机
    @Override
    public String streamingCraneReport(int checkId, int projectId, String checkPart, int fourthId) {
        String ftlName = "streamingCrane";
        return equipReport(checkId, projectId, checkPart, fourthId, ftlName);
    }

    //附着式升降脚手架
    @Override
    public String insertedLiftScaffoldReport(int checkId, int projectId, String checkPart, int fourthId) {
        String ftlName = "insertedLiftScaffold";
        return equipReport(checkId, projectId, checkPart, fourthId, ftlName);

    }

    @Override
    public String highWorkHangingBasketReport(int checkId, int projectId, String checkPart, int fourthId) {
        String ftlName = "highWorkHangingBasket";
        return equipReport(checkId, projectId, checkPart, fourthId, ftlName);
    }

    public void initWordTheme() {
        StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
        //设置标题字体
        standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 20));
        //设置图例的字体
        standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));
        //设置轴向的字体
        standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));
        //应用主题样
        ChartFactory.setChartTheme(standardChartTheme);
    }

    public void initWordDate(Map<String, Object> dataMap) {
        Date date = new Date();
        dataMap.put("day", new SimpleDateFormat("dd").format(date));
        dataMap.put("month", new SimpleDateFormat("MM").format(date));
        dataMap.put("year", new SimpleDateFormat("yyyy").format(date));
        //dataMap.put("fileName", new SimpleDateFormat("yyyyMMddhhmmss").format(date));
    }

    public void initProjectProfiles(Map<String, Object> dataMap) {
        dataMap.put("zlWeight", "\\");
        dataMap.put("aqWeight", "\\");
        dataMap.put("glWeight", "\\");
        dataMap.put("zlWeight", newPrefixSystemMapper.getWeight1ByName1("新质量检查"));
        dataMap.put("aqWeight", newPrefixSystemMapper.getWeight1ByName1("新安全检查"));
        dataMap.put("glWeight", newPrefixSystemMapper.getWeight1ByName1("新管理行为"));
        dataMap.put("zlPoint", "\\");
        dataMap.put("glPoint", "\\");
        dataMap.put("aqPoint", "\\");
    }

    public void initProjectMachineInfo(Map<String, Object> dataMap, int projectId) {
        List<MachineInfo> machineInfoList = machineinfoMapper.getEquipTypeByProjectId(projectId);
        List<Object> equipList = new ArrayList<Object>();
        if (machineInfoList.size() == 0) {
            Map<String, Object> eqMap = new HashMap<String, Object>();
            eqMap.put("equipId", "\\");
            eqMap.put("equipType", "\\");
            eqMap.put("equipQua", "\\");
            eqMap.put("equipNum", "\\");
            eqMap.put("equipLeaseUnit", "\\");
            eqMap.put("equipUseUnit", "\\");
            eqMap.put("demolitionUnit", "\\");
            eqMap.put("testUnit", "\\");
            equipList.add(eqMap);
        } else {
            for (int i = 0; i < machineInfoList.size(); i++) {
                Map<String, Object> eqMap = new HashMap<String, Object>();
                MachineInfo machineInfo = machineInfoList.get(i);
                eqMap.put("equipId", machineInfo.getmKey());
                int temp = 0;
                if (machineInfo.getMachineType() != null) {
                    temp = machineInfo.getMachineType();
                    String equipType = newPrefixSystemMapper.getName4ByName4Id(temp);
                    eqMap.put("equipType", equipType);
                } else {
                    eqMap.put("equipType", "？？？");
                }
                String factoryNum = machineInfo.getFactoryNum();
                int count = 1;
                try {
                    count = Integer.parseInt(factoryNum);
                    if (count > 100) {
                        count = 1;
                    }
                    ;
                } catch (Exception e) {
                    count = 1;
                }
                eqMap.put("equipQua", count);
                eqMap.put("equipNum", machineInfo.getEquipNum());
                eqMap.put("equipLeaseUnit", machineInfo.getRentalUnit());
                eqMap.put("equipUseUnit", machineInfo.getUseUnit());
                eqMap.put("demolitionUnit", machineInfo.getInstallRemoveUnit());
                eqMap.put("testUnit", machineInfo.getDetectionUnit());
                equipList.add(eqMap);
            }
        }
        dataMap.put("equipList", equipList);
    }

    public Set<Integer> getThirdSet(int checkId) {
        Set<Integer> thirdSet = new HashSet<>();
        List<ProblemCollectDetail> pcdList = newProblemCollectDetailMapper.getAllInfoByCheck(String.valueOf(checkId));
        for (ProblemCollectDetail problemCollectDetail : pcdList) {
            if (!thirdSet.contains(problemCollectDetail.getThirdId())) {
                thirdSet.add(problemCollectDetail.getThirdId());
            }
        }
        return thirdSet;
    }

    public void initProjectSummaryFirstPart(int projectId, Map<String, Object> dataMap) {
        ContractTaskProject contractTaskProject = contractTaskProjectMapper.selectAllByProjectId(projectId);
        System.out.println("======"+contractTaskProject.toString());
        if (contractTaskProject != null) {
            dataMap.put("projectName", contractTaskProject.getProjectName());
            dataMap.put("projectAddress", contractTaskProject.getArea());
            dataMap.put("jsUnit", contractTaskProject.getJsUnit());
            dataMap.put("jlUnit", contractTaskProject.getJlUnit());
            dataMap.put("sgUnit", contractTaskProject.getSgUnit());
            dataMap.put("projectType", contractTaskProject.getProjectType());
            dataMap.put("projectPrice", contractTaskProject.getProjectPrice());
            dataMap.put("dangerItem", contractTaskProject.getDangerItem());
            dataMap.put("remark", contractTaskProject.getRemark());
            dataMap.put("projectDescription", contractTaskProject.getProjectDescription());
            dataMap.put("jsUniter", contractTaskProject.getJsUniter());
            dataMap.put("jlUniter", contractTaskProject.getJlUniter());
            dataMap.put("sgUniter", contractTaskProject.getManager());
        }
    }


}
